﻿


using IotClientService.Enums;
using IotClientService.Extensions;
using IotClientService.Handles.hks;
using IotContract.Dtos.Clients;
using IotContract.Dtos.Clients.Equips;
using IotContract.Enums;
using IotContract.Events;
using IotContract.Interfaces;
using IotContract.Models;
using IotContract.Models.Clients.Hks;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using XT.Common.Enums;
using XT.Common.Extensions;

namespace IotClientService.Handles;
public class OcvFmtTcpHandle
{


    public event EventHandler<ConnectStatusEventArgs> OnConnectLogChanged;
    public HkOcvFmtEquipDto Group { get; set; }







    private string CLIENT_IMS_ID = "IMS";




    private int[] TxCnt = new int[101];




    private string[] TxMsg = new string[101];




   



    private TcpClient _tcpClient;

    private NetworkStream _stream;

    private XmlSub _sub = new XmlSub();

    private string RxMsg = String.Empty;

    private int RxCnt = 0;


    private ConnectTypeEnum _connectType;
   

    public string SetDateTimeReq = "";

    private bool _curConnection = false;

    private IConnectDataService _connectDataService;

    public OcvFmtTcpHandle()
    {
        for (int i = 0; i < (int)this.TxCnt.Length; i++)
        {
            this.TxCnt[i] = 0;
            this.TxMsg[i] = "";
        }


    }

    public bool GetConnection()
    {
        try
        {
            if (_tcpClient == null) return false;

            if (_tcpClient == null || _tcpClient.Connected == false ||
                      _tcpClient.Client.Poll(1, SelectMode.SelectRead) == true && _tcpClient.Available == 0)
            {
                return false;
            }
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }

    }

    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="connectDataService"></param>
    /// <returns></returns>
    public bool Init(IConnectDataService connectDataService,HkOcvFmtEquipDto equip)
    {
        _connectDataService = connectDataService;
        Group = equip;
        return true;
    }


    public string PCHeaderMessage(HkOcvFmtEquipDto group, string bdata, string rscommand, string retcode, int datalength)
    {
        string sdata = "@";
        sdata = string.Concat(sdata, group.LineNo.Trim().PadRight(4, ' '));
        sdata = string.Concat(sdata, CLIENT_IMS_ID.Trim().PadRight(8, ' '));
        // ocvxx
        sdata = string.Concat(sdata, group.Name.Trim().PadRight(8, ' '));
        sdata = string.Concat(sdata, string.Format("{0:0000}", rscommand));
        sdata = string.Concat(sdata, string.Format("{0:yyyyMMddHHmmss}", DateTime.Now));
        sdata = string.Concat(sdata, retcode.PadLeft(4, ' '));
        sdata = string.Concat(sdata, string.Format("{0:000000}", datalength));
        sdata = string.Concat(sdata, ":");
        sdata = string.Concat(sdata, bdata);
        sdata = string.Concat(sdata, "*;");
        return sdata;
    }





    public string ConnectServer(HkOcvFmtEquipDto group)
    {
        if (_connectType == ConnectTypeEnum.Connecting) return String.Empty;
        Group = group;
        string message = "";
        try
        {
            // 解析ipaddress
            var ips = group.IPAddress.Split(":");
            if (ips.Length != 2)
            {
                return string.Empty;
            }
            string ipAddress = ips[0];
            int port = ips[1].To<int>();

            _tcpClient = new TcpClient(ipAddress, port)
            {
                ReceiveTimeout = 50,
                SendTimeout = 50
            };




            _stream = _tcpClient.GetStream();


            _stream.ReadTimeout = 100;



            var str = HbcExtension.GenerateHeaderMessage(Group, "", "0002", "0");
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            _stream.Write(bytes, 0, (int)bytes.Length);

            _curConnection = true;
            _connectType = ConnectTypeEnum.Connected;
            OnConnectLogChanged?.Invoke(this, new  ConnectStatusEventArgs
            {
                Connect = true,
               
                IsSuccess = true

            });

        }
        catch (Exception exception)
        {
            _connectType = ConnectTypeEnum.Stop;
            message = exception.Message;
            OnConnectLogChanged?.Invoke(this, new ConnectStatusEventArgs
            {
                Connect = false,
               
                Message = exception.Message,
                IsSuccess = false
            });
        }
        return message;
    }



    public void DisconnectServer()
    {
        try
        {
            if (_stream?.Socket?.Connected==true)
            {
                _stream?.Close();
            }
            if (_tcpClient?.Connected==true)
            {
                _tcpClient?.Close();
            }
           
            _curConnection = false;
            OnConnectLogChanged?.Invoke(this, new ConnectStatusEventArgs
            {
                Connect = false,
                IsSuccess = true,
                

            });
        }
        catch (Exception exception)
        {
            OnConnectLogChanged?.Invoke(this, new ConnectStatusEventArgs
            {
                Connect = false,
                Message = exception.Message,
               
                IsSuccess = false

            });
        }
    }

    public async Task Execute()
    {
        if (_tcpClient == null || !_tcpClient.Connected) return;

        try
        {
            if (_stream != null && _stream.CanRead)
            {

                byte[] numArray = new byte[5000000];
                int num3 = await _stream.ReadAsync(numArray, 0, (int)numArray.Length);
                string str = string.Empty;
                int length = 0;
                int num = -1;
                int num1 = -1;
                int num2 = -1;

                if (num3 > 0)
                {
                    str = Encoding.UTF8.GetString(numArray, 0, num3);
                    length = str.Length;
                    if (RxCnt > 5000000)
                    {
                        RxCnt = 0;
                    }
                    num = str.IndexOf("@");
                    num1 = str.IndexOf("*");
                    num2 = str.IndexOf(";");

                    if ((num < 0 && num2 < 0))
                    {

                        RxCnt = RxCnt + length;

                        RxMsg = string.Concat(RxMsg, str);
                    }
                    else if ((num >= 0 && num2 < 0))
                    {
                        RxCnt = 0;
                        RxMsg = "";

                        RxCnt = RxCnt + length;

                        RxMsg = string.Concat(RxMsg, str);
                    }
                    else if ((num < 0 && num2 >= 0))
                    {
                        RxCnt = RxCnt + num2 + 1;

                        RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, 1, num2 + 1));
                        str = _sub.Lf_Copy(str, num2 + 2, length);

                        await ExecuteData(RxMsg);
                        RxCnt = 0;
                        RxMsg = "";
                        Group.ReadTime = DateTime.Now;

                        RxCnt = RxCnt + str.Length;

                        RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, 1, RxCnt));
                        str = _sub.Lf_Copy(str, 1, RxCnt);
                    }
                    else if ((num >= 0 && num2 >= 0))
                    {
                        if (num >= num2)
                        {

                            RxCnt = RxCnt + num2 + 1;

                            RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, 1, num2 + 1));
                            str = _sub.Lf_Copy(str, num2 + 2, length);

                            await ExecuteData(RxMsg);
                            RxCnt = 0;
                            RxMsg = "";
                            Group.ReadTime = DateTime.Now;

                            RxCnt = RxCnt + str.Length;

                            RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, 1, RxCnt));
                            str = _sub.Lf_Copy(str, 1, RxCnt);
                        }
                        else
                        {
                            RxCnt = 0;
                            RxMsg = "";

                            RxCnt = RxCnt + num2 - num + 1;

                            RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, num + 1, num2 + 1));
                            str = _sub.Lf_Copy(str, num2 + 2, length);

                            await ExecuteData(RxMsg);
                            RxCnt = 0;
                            RxMsg = "";
                            Group.ReadTime = DateTime.Now;

                            RxCnt = RxCnt + str.Length;

                            RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, 1, RxCnt));
                            str = _sub.Lf_Copy(str, 1, RxCnt);
                        }
                        while (true)
                        {
                            num = str.IndexOf("@");
                            num1 = str.IndexOf("*");
                            num2 = str.IndexOf(";");
                            if (num < 0 || num2 < 0)
                            {
                                break;
                            }
                            if (num >= num2)
                            {
                                RxCnt = RxCnt + num2 + 1;

                                RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, 1, num2 + 1));
                                str = _sub.Lf_Copy(str, num2 + 2, length);

                                await ExecuteData(RxMsg);
                                RxCnt = 0;
                                RxMsg = "";
                                Group.ReadTime = DateTime.Now;

                                RxCnt = RxCnt + str.Length;

                                RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, 1, RxCnt));
                                str = _sub.Lf_Copy(str, 1, RxCnt);
                            }
                            else
                            {
                                RxCnt = 0;
                                RxMsg = "";

                                RxCnt = RxCnt + num2 - num + 1;

                                RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, num + 1, num2 + 1));
                                str = _sub.Lf_Copy(str, num2 + 2, length);

                                await ExecuteData(RxMsg);
                                RxCnt = 0;
                                RxMsg = "";
                                Group.ReadTime = DateTime.Now;

                                RxCnt = RxCnt + str.Length;

                                RxMsg = string.Concat(RxMsg, _sub.Lf_Copy(str, 1, RxCnt));
                                str = _sub.Lf_Copy(str, 1, RxCnt);
                            }
                        }

                    }
                }
            }

        }
        catch (OperationCanceledException operationCanceledException)
        {
            DisconnectServer();
            OnConnectLogChanged?.Invoke(this, new ConnectStatusEventArgs
            {
                Connect = false,
              
                Message = operationCanceledException.Message,
                IsSuccess = false
            });

        }
        catch (SocketException socketException)
        {

            DisconnectServer();
            OnConnectLogChanged?.Invoke(this, new ConnectStatusEventArgs
            {
                Connect = false,
                
                Message = socketException.Message,
                IsSuccess = false
            });

        }
        catch (Exception exception)
        {

            OnConnectLogChanged?.Invoke(this, new ConnectStatusEventArgs
            {
                Connect = _tcpClient.Connected,
              
                Message = exception.Message,
                IsSuccess = true
            });

        }

    }


    public async Task ExecuteData(string rxMsg)
    {

        Task.Factory.StartNew(async (msg) =>
        {
            var parser = _sub.XmlDocParsing(msg.ToString(), Group);


            var errorParse = await ParseMsg(parser);
        }, rxMsg);



    }


    public async Task COM_SendMessage0002()
    {
        string str = "0";

        //if (Group.EquipType ==HKEquipType.ECS )
        //{
        //  var time=  await DataManager.SyncPcToDbTime();
        //}

        string str1 = HbcExtension.GenerateHeaderMessage(Group, "", "0002", "0");
        await SendDataToHk(str1);
        SetDateTimeReq = DateTime.Now.ToString("yyyyMMdd");
        Group.ReadTime = DateTime.Now;
    }


    /// <summary>
    /// 解析数据
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task<string> ParseMsg(ParserDefine parser)
    {
        if (parser.LineNo != Group.LineNo)
        {
            return $"{Group.ToString()} No Match LineNo";
        }
        if (parser.FrMsg != Group.Name.ToUpper())
        {
            return $"{Group.ToString()} No Match EquipNo";
        }
        if (parser.ToMsg == CLIENT_IMS_ID)
        {
            Group.ReadTime = DateTime.Now;
            if ((parser.RetCode != "0" && parser.RetCode != "0000"))
            {
            }
            // Group.EvtMsg = string.Concat(new object[] { "Rx ", parser.Command, _sub.Lf_iif(parser.StageNo == "", "", string.Concat(" (", parser.StageNo, ")")), _sub.Lf_iif(parser.TrayID == "", "", string.Concat(" :", parser.TrayID)), _sub.Lf_iif(parser.TrayID2 == "", "", string.Concat(",", parser.TrayID2)), _sub.Lf_iif(parser.TrayID3 == "", "", string.Concat(",", parser.TrayID3)), _sub.Lf_iif(parser.TrayID4 == "", "", string.Concat(",", parser.TrayID4)), _sub.Lf_iif(parser.TrayID5 == "", "", string.Concat(",", parser.TrayID5)), _sub.Lf_iif(parser.TrayID6 == "", "", string.Concat(",", parser.TrayID6)) });
            if (parser.Command == "1001")
            {
                await COM_ReceiveMessage1001(parser);
                return String.Empty;
            }
            else if (parser.Command == "1002")
            {
                await COM_ReceiveMessage1002();
                return String.Empty;
            }

            else if (parser.Command == "1012")
            {

                await COM_ReceiveMessage1012(parser);
                return String.Empty;
            }

            if (Group.EquipType ==IotEquipType.FMT.ToString())
            {
                // 设备库位应答
                if (parser.Command == "1101")
                {
                    await FMT_ReceiveMessage1101(parser);
                }
                // 预约后设备应答
                else if (parser.Command == "1102")
                {
                    await FMT_ReceiveMessage1102(parser);
                }
                // 入库通知设备应答
                else if (parser.Command == "1103")
                {
                    await FMT_ReceiveMessage1103(parser);
                }
                // 检查结束通知
                else if (parser.Command == "1104")
                {
                    await FMT_ReceiveMessage1104(parser);
                }
                // 结果应答
                else if (parser.Command == "1105")
                {
                    await FMT_ReceiveMessage1105(parser);
                }
                else if (parser.Command == "1106")
                {
                    await FMT_ReceiveMessage1106(parser);
                }
                else if (parser.Command == "1107")
                {
                    await FMT_ReceiveMessage1107(parser);
                }
                else if (parser.Command == "1108")
                {
                    await FMT_ReceiveMessage1108(parser);
                }
                else if (parser.Command == "1109")
                {
                    await FMT_ReceiveMessage1109(parser);
                }
                // 充放电移库
                else if (parser.Command == "1110")
                {
                    await FMT_ReceiveMessage1110(parser);
                }
                // 复测
                else if (parser.Command == "1112")
                {
                    await FMT_ReceiveMessage1112(parser);
                }
            }
            else if ((Group.EquipType == IotEquipType.OCV.ToString()))
            {
                if (parser.Command == "1201")
                {
                    await OCV_ReceiveMessage1201(parser);
                }
                else if (parser.Command == "1202")
                {
                    await OCV_ReceiveMessage1202(parser);
                }
                else if (parser.Command == "1203")
                {
                    await OCV_ReceiveMessage1203(parser);
                }
                else if (parser.Command == "1204")
                {
                    OCV_ReceiveMessage1204();
                }
                else if (parser.Command == "1205")
                {
                    OCV_ReceiveMessage1205();
                }
                else if (parser.Command == "1206")
                {
                    await OCV_ReceiveMessage1206(parser);

                }
                else if (parser.Command == "1207")
                {
                    await OCV_ReceiveMessage1207(parser);

                }
                else if (parser.Command == "1208")
                {
                    Group.Mode = parser.Mode;
                }
                else if (parser.Command == "1209")
                {
                    await OCV_ReceiveMessage1209(parser);
                }
            }
            //else if (Group.EquipType == HKEquipType.RNK)
            //{
            //    if (parser.Command == "1601")
            //    {
            //        await RNK_ReceiveMessage1601();
            //    }
            //    else if (parser.Command == "1602")
            //    {
            //        await RNK_ReceiveMessage1602(parser);
            //    }
            //    else if (parser.Command == "1603")
            //    {
            //        await RNK_ReceiveMessage1603(parser);
            //    }
            //    else if (parser.Command == "1604")
            //    {
            //        await RNK_ReceiveMessage1604();
            //    }
            //    else if (parser.Command == "1608")
            //    {
            //        RNK_ReceiveMessage1608();
            //    }
            //    else if (parser.Command == "1609")
            //    {
            //        await RNK_ReceiveMessage1609(parser);
            //    }
            //}
            //else if (Group.EquipType == HKEquipType.CPK)
            //{
            //    if (parser.Command == "1701")
            //    {
            //        await CPK_ReceiveMessage1701(parser);
            //    }
            //    else if (parser.Command == "1702")
            //    {
            //        await CPK_ReceiveMessage1702(parser);
            //    }
            //    else if (parser.Command == "1703")
            //    {
            //        await CPK_ReceiveMessage1703(parser);
            //    }
            //    else if (parser.Command == "1704")
            //    {
            //        await CPK_ReceiveMessage1704(parser);
            //    }
            //    else if (parser.Command == "1705")
            //    {
            //        await CPK_ReceiveMessage1705(parser);
            //    }
            //    else if (parser.Command == "1706")
            //    {
            //        await CPK_ReceiveMessage1706(parser);
            //    }
            //    else if (parser.Command == "1707")
            //    {
            //        await CPK_ReceiveMessage1707(parser);
            //    }
            //    else if (parser.Command == "1708")
            //    {
            //        await CPK_ReceiveMessage1708();
            //    }
            //    else if (parser.Command == "1709")
            //    {
            //        await CPK_ReceiveMessage1709(parser);
            //    }
            //}


        }
        else
        {
            return $"{Group.ToString()} ToMsg  No Match IMS";
        }

        return string.Empty;
    }


    /// <summary>
    /// 心跳应答
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task COM_ReceiveMessage1001(ParserDefine parser)
    {
        if (parser.RetCode == "0")
        {


            string str1 = "";
            string str2 = "";
            str1 = HbcExtension.GenerateHeaderMessage(Group, str2, "0001", "1");

            await SendDataToHk(str1);

        }
    }
    /// <summary>
    /// 时间应答 获取库位信息
    /// </summary>
    /// <returns></returns>
    public async Task COM_ReceiveMessage1002()
    {

        if (Group.EquipType == IotEquipType.FMT.ToString())
        {
            string str = "";
            string str1 = "";
            // 获取库位信息
            str = HbcExtension.GenerateHeaderMessage(Group, str1, "0101", "0");



            await SendDataToHk(str);

        }
    }
    /// <summary>
    /// 获取库位
    /// </summary>
    /// <returns></returns>
    public async Task COM_GetStages()
    {
        if (Group.EquipType == IotEquipType.FMT.ToString())
        {
            string str = "";
            string str1 = "";
            // 获取库位信息
            str = HbcExtension.GenerateHeaderMessage(Group, str1, "0101", "0");
            await SendDataToHk(str);

        }
    }



    #region 数据库逻辑
    /// <summary>
    /// 设备Error通知
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task COM_ReceiveMessage1012(ParserDefine parser)
    {
        var refMsg = parser.StageNo.PadRight(4, ' ');
        if (Group.EquipType == IotEquipType.FMT.ToString())
        {

            Group.Value = parser.StageNo + "-" + parser.ErrCode;
        }
        else
        {
            Group.Value = parser.ErrCode;
        }

        if (parser.ErrCode == "02" || parser.ErrCode == "03" || parser.ErrCode == "26")
        {
           
            // 调用报警逻辑
            var result = await _connectDataService.CommitFireWarn(new IotEquipWarnDto
            {
                EquipType = Group.EquipType,
                ProtobufType=IotProtobufType.HK_OCVFMT.ToString(),
                Data = $"{Group.Name}*{parser.StageNo}",
                ErrorCode = parser.ErrCode,
                ErrorTime = DateTime.Now,
                EquipId = Group.Id
            });

            if (!result.IsSuccess)
            {
                await Task.Delay(500);
                await _connectDataService.CommitFireWarn(new IotEquipWarnDto
                {
                    EquipType = Group.EquipType,
                    ProtobufType = IotProtobufType.HK_OCVFMT.ToString(),
                    Data = $"{Group.Name}*{parser.StageNo}",
                    ErrorCode = parser.ErrCode,
                    ErrorTime = DateTime.Now,
                    EquipId = Group.Id
                });
            }
        }

        var msg = HbcExtension.GenerateHeaderMessage(Group, refMsg, "0012", "0");

        await SendDataToHk(msg);

    }


    // 接收库位状态
    public async Task FMT_ReceiveMessage1101(ParserDefine parser)
    {
        if (parser.RetCode != "0")
        {
            return;
        }
        if (parser.Stage == null || parser.Stage.Length == 0)
        {
            return;
        }

        // 库位赋值
        Group.Stages = parser.Stage.ToList();

    }
    /// <summary>
    /// 预约后直接对库位赋值
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task FMT_ReceiveMessage1102(ParserDefine parser)
    {

        var stage = Group.Stages.FirstOrDefault(x => x.StageNo == parser.StageNo);
        if (stage != null)
        {
            stage.StageStatus = "6";
        }

    }

    /// <summary>
    /// 入库通知应答
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task FMT_ReceiveMessage1103(ParserDefine parser)
    {

        var result = int.TryParse(parser.StageNo, out int stage);

        if (!result)
        {
            return;
        }

    }
    // 1104 检查结束通知
    public async Task FMT_ReceiveMessage1104(ParserDefine parser)
    {
        var result = int.TryParse(parser.StageNo, out int stage);

        if (!result)
        {
            Log($"1104 stageNo error {parser.StageNo}", LogEnum.Error);
        }

        string text4 = "";
        text4 += parser.StageNo.PadLeft(4, ' ');
        // 发送收到应答
        var msg = HbcExtension.GenerateHeaderMessage(Group, text4, "0104", "0");
        await SendDataToHk(msg);
        text4 = "";
        text4 += parser.StageNo.PadLeft(4, ' ');
        text4 += parser.TrayID.PadRight(7, ' ');
        // 自动请求结果
        msg = HbcExtension.GenerateHeaderMessage(Group, text4, "0105", "0");
        await SendDataToHk(msg);
    }



    // 确认结果数据
    public async Task FMT_ReceiveMessage1105(ParserDefine parser)
    {

        Log($"收到库位测试结果 {parser.StageNo} {parser.TrayID}", LogEnum.Info);
        string str13 = "";
        str13 = string.Concat(str13, parser.StageNo.PadLeft(4, ' '));
        // 0 ok  1 ng
        str13 = string.Concat(str13, "0");
        str13 = string.Concat(str13, parser.TrayID.PadRight(7, ' '));

        // 发送数据

        if (parser.Step == null || parser.Step.Count() == 0)
        {
            // 发送接收确认
            var str14 = HbcExtension.GenerateHeaderMessage(Group, str13, "0106", "0");

            await SendDataToHk(str14);

            var stage = Group.Stages.FirstOrDefault(x => x.StageNo == parser.StageNo);
            if (stage != null)
            {
                // 22585  22587
                stage.Status = 2;
            }
            return;
        }

        try
        {

            ChargeTrayResult trayResult = new ChargeTrayResult();
            List<ChargeResult> charges = new List<ChargeResult>();

            foreach (var step in parser.Step)
            {
                ChargeResult charge = new ChargeResult();

                charge.TrayNo = parser.TrayID;

                // charge.TrayNo = "A179074";


                List<ChargeDetail> details = new List<ChargeDetail>();
                int channel = 0;
                if (step.Action.IsNullOrEmpty())
                {
                    continue;
                }
                foreach (var slot in step.Slot)
                {
                    channel++;
                    var detail = new ChargeDetail();
                    detail.Lotno = parser.LotNo;
                    detail.Channel = channel;
                    detail.ChargeStep = int.Parse(step.StepNo);
                    detail.VoltageStart = slot.VoltSt;
                    detail.VoltageEnd = slot.VoltEd;
                    detail.VoltageLineStart = slot.StFrVolt;
                    detail.VoltageLineEnd = slot.EdFrVolt;

                    detail.CurrentStart = slot.CurrSt;
                    detail.CurrentEnd = slot.CurrEd;

                    detail.CapacityStart = slot.CapaSt;
                    detail.CapacityEnd = slot.CapaEd;

                    detail.EnergyStart = slot.StCapa;
                    detail.EnergyEnd = slot.FnCapa;



                    detail.NgCode = parser.Step[0].Slot[channel - 1].NgCode;

                    detail.StartTime = DateTime.ParseExact(parser.TimeS, "yyyyMMddHHmmss", null).ToString("yyyy-MM-dd HH:mm:ss");
                    detail.EndTime = DateTime.ParseExact(parser.TimeE, "yyyyMMddHHmmss", null).ToString("yyyy-MM-dd HH:mm:ss");

                    detail.TemperatureMax = step.Slot[0].Jig_tMx;
                    detail.TemperatureMin = step.Slot[0].Jig_tMn;
                    detail.TemperatureAvg = step.Slot[0].Jig_tAv;

                    detail.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    detail.EquipmentCode = Group.Num.ToString();

                    details.Add(detail);

                    // 平均电压

                    // 放电时间

                    // 充电时间

                    // 终止时间


                }
                charge.ChargeDetails = details;

                charges.Add(charge);
            }

            trayResult.ChargeResultsVos = charges;

            trayResult.Temps = parser.Temperatures;


            trayResult.Stage = int.Parse(parser.StageNo);

            trayResult.GroupNumber = Group.Num.To<int>();

            await CallFmtResult(trayResult, str13);



        }
        catch (Exception ex)
        {
            Log(ex.Message, LogEnum.Error);
        }
    }

    /// <summary>
    /// 提交结果
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    private async Task CallFmtResult(ChargeTrayResult data, string msg)
    {
        try
        {
            var result = await _connectDataService.CommitChargeFMTResult(data);

            if (result.IsSuccess)
            {
                Log($"提交库位测试结果成功 {data.Stage} {data.ChargeResultsVos[0].TrayNo} {result.Data}", LogEnum.Info);
                Group.Value = $"提交库位测试结果成功 {data.Stage} {data.ChargeResultsVos[0].TrayNo} {result.Data}";
                // 发送接收确认
                var str14 = HbcExtension.GenerateHeaderMessage(Group, msg, "0106", "0");

                bool sendResult = await SendDataToHk(str14);

                if (!sendResult)
                {
                    sendResult = await SendDataToHk(str14);
                }
                return;


            }
            else
            {
                Log($"提交库位测试结果失败 {data.Stage} {data.ChargeResultsVos[0].TrayNo} {result.Msg}", LogEnum.Error, false);
                Group.Value = $"提交库位测试结果失败 {data.Stage} {data.ChargeResultsVos[0].TrayNo} {result.Msg}";


            }
        }
        catch (Exception ex)
        {
            Log($"提交库位测试结果失败 {data.Stage} {data.ChargeResultsVos[0].TrayNo} {ex.Message}", LogEnum.Error, false);
            Group.Value = $"提交库位测试结果失败 {data.Stage} {data.ChargeResultsVos[0].TrayNo} {ex.Message}";
        }



    }


    public async Task FMT_ReceiveMessage1106(ParserDefine parser)
    {

    }

    public async Task FMT_ReceiveMessage1107(ParserDefine parser)
    {

    }

    public async Task FMT_ReceiveMessage1108(ParserDefine parser)
    {

    }

    public async Task FMT_ReceiveMessage1109(ParserDefine parser)
    {
        Log($"收到库位更新数据 {parser.StageNo} {parser.StageStatus}", LogEnum.Info);

        if (Group.Stages != null && Group.Stages.Count > 0)
        {
            var stage = Group.Stages.FirstOrDefault(x => x.StageNo == parser.StageNo);
            if (stage == null) return;
            stage.StageStatus = parser.StageStatus.Trim();
            stage.StageMode = parser.StageMode.Trim();
        }
    }
    /// <summary>
    /// 设备充放电移库
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task FMT_ReceiveMessage1110(ParserDefine parser)
    {
        Log($"收到充放电移库数据 {parser.StageNo} {parser.TrayID} {parser.AlarmMsg}", LogEnum.Info);

        var trayData = await _connectDataService.CommitFmtMove(new StageMoveInstruct
        {
            CurrLocCode = parser.StageNo,
            TrayNo = parser.TrayID,
            Reason = parser.AlarmMsg
        });
        if (!trayData.IsSuccess)
        {
            var msg = $"{parser.StageNo} 充放电移库通知失败 {trayData.Msg}";
            Log(msg, LogEnum.Error, false);

            Group.Value = msg;
            return;
        }
        else
        {
            Log($"{parser.StageNo} 充放电移库通知成功", LogEnum.Info);
            Group.Value = $"{parser.StageNo} 充放电移库通知成功";
        }
        string sendMsg = string.Empty;
        sendMsg = string.Concat(sendMsg, parser.StageNo.PadLeft(4, ' '));
        // 新库位
        sendMsg = string.Concat(sendMsg, trayData.Data.PadLeft(4, ' '));

        var data = HbcExtension.GenerateHeaderMessage(Group, sendMsg, "0110", "0");
        bool sendResult = await SendDataToHk(data);

        if (!sendResult)
        {
            await SendDataToHk(data);
        }


    }

    /// <summary>
    /// 设备充放电复测
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task FMT_ReceiveMessage1112(ParserDefine parser)
    {
        Log($"收到充放电复测数据 {parser.StageNo} {parser.TrayID} {parser.AlarmMsg} {(parser.Mode == "1" ? "重新作业" : "复测")}", LogEnum.Info);
        string sendMsg = string.Empty;
        sendMsg = string.Concat(sendMsg, parser.StageNo.PadLeft(4, ' '));


        var data = HbcExtension.GenerateHeaderMessage(Group, sendMsg, "0112", "0");
        bool sendResult = await SendDataToHk(data);

        if (!sendResult)
        {
            await SendDataToHk(data);
        }
        Log($"充放电 {parser.StageNo} {parser.TrayID} {parser.AlarmMsg} {(parser.Mode == "1" ? "重新作业" : "复测")}  回复成功", LogEnum.Info);


        // 如果不是重新作业，需要获取复测配方重新预约

        int.TryParse(parser.StageNo, out int stage);
        bool result = false;
        // 重新作业
        if (parser.Mode == "1")
        {
            // 开始重新预约获取配方并发送
            result = await FMT_SendMessage0102(Group, new HkWriteInstruct
            {
                Num = Group.Num,
                TrayID = parser.TrayID,
                Stage = stage
            }, 2);
        }
        else
        {
            // 开始重新预约获取复测配方并发送
            result = await FMT_SendMessage0102(Group, new HkWriteInstruct
            {
                Num = Group.Num,
                TrayID = parser.TrayID,
                Stage = stage
            }, 1);
        }




        if (!result)
        {
            Log($"充放电 {parser.StageNo} {parser.TrayID} {parser.AlarmMsg}  {(parser.Mode == "1" ? "重新作业" : "复测")} 失败", LogEnum.Info, false);
            return;
        }
    }

    /// <summary>
    /// OCV 通知托盘ID
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task OCV_ReceiveMessage1201(ParserDefine parser)
    {
        if (Group.TrayNo == parser.TrayID)
        {
            // 已经在调用中
            if (Group.Status == 1)
            {
                return;
            }
        }

        Group.TrayNo = parser.TrayID;
        Group.Status = 1;
        var trayData = await _connectDataService.GetTrayCellStatus(new TrayDefineInstruct
        {
            TrayNo = parser.TrayID,
            StageNo = parser.StageNo,
            GroupNumber = Group.Num.To<int>(),
        });
        if (!trayData.IsSuccess)
        {
            var msg = $"{parser.TrayID} 获取OCV组盘信息失败 {trayData.Msg}";
            Log(msg, LogEnum.Error, false);
            var error = HbcExtension.GenerateHeaderMessage(Group, "", "0201", trayData.Code.ToString());
            await SendDataToHk(error);


            Group.Value = msg;
            Group.Status = 0;
            return;
        }
        else
        {
            Log($"{parser.TrayID} 获取OCV组盘信息成功", LogEnum.Info);
            Group.Value = $"{parser.TrayID} 获取OCV组盘信息成功";
        }
        var tray = trayData.Data;
        string str7 = "";
        str7 = string.Concat(str7, tray.EquipmentCode.PadLeft(4, ' '));
        str7 = string.Concat(str7, tray.RouterCode.PadLeft(4, ' '));
        str7 = string.Concat(str7, tray.StepNo.ToString().PadLeft(2, ' '));
        str7 = string.Concat(str7, tray.LotNo.PadLeft(10, ' '));
        str7 = string.Concat(str7, tray.TrayNo.PadLeft(7, ' '));
        str7 = string.Concat(str7, tray.OptType.ToString().PadLeft(1, ' '));
        // cellinfo 1*400

        foreach (var cell in tray.Cells)
        {
            str7 = string.Concat(str7, cell.State.ToString().PadLeft(1, ' '));
        }
        var data = HbcExtension.GenerateHeaderMessage(Group, str7, "0201", "0");
        bool sendResult = await SendDataToHk(data);

        if (!sendResult)
        {
            await SendDataToHk(data);
        }
        Group.Status = 0;

    }

    /// <summary>
    /// 检查结束通知
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task OCV_ReceiveMessage1202(ParserDefine parser)
    {
        var str = parser.StageNo.PadLeft(4, ' ');
        string str4 = "";
        str4 = HbcExtension.GenerateHeaderMessage(Group, str, "0202", "0");
        await SendDataToHk(str4);

        if (parser.RetCode == "2") return;

        str = String.Empty;

        str = string.Concat(str, parser.StageNo.PadLeft(4, ' '));
        str = string.Concat(str, parser.TrayID.PadRight(7, ' '));
        // 请求结果
        var data = HbcExtension.GenerateHeaderMessage(Group, str, "0203", "0");
        await SendDataToHk(data);



    }
    /// <summary>
    /// 接收测试结果
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task OCV_ReceiveMessage1203(ParserDefine parser)
    {
        Log($"{Group.ToString()}接收数据成功", LogEnum.Info);
        string str1 = String.Empty;
        str1 = string.Concat(str1, parser.StageNo.PadLeft(4, ' '));



        try
        {

            OCVTrayResult oCVTrayResults = new OCVTrayResult();
            List<CellDetail> details = new List<CellDetail>();


            if (parser.Step != null && parser.Step.Count() > 0)
            {
                var step = parser.Step[0];
                OCVTrayResult oCVTrayResult = new OCVTrayResult();
                oCVTrayResult.EquipmentCode = Group.Num;
                oCVTrayResult.TrayNo = parser.TrayID;
                oCVTrayResult.GroupNumber = Group.Num.To<int>();
                oCVTrayResult.StartTime = DateTime.ParseExact(parser.TimeS, "yyyyMMddHHmmss", null).ToString("yyyy-MM-dd HH:mm:ss");
                oCVTrayResult.EndTime = DateTime.ParseExact(parser.TimeE, "yyyyMMddHHmmss", null).ToString("yyyy-MM-dd HH:mm:ss");

                int channel = 0;



                foreach (var slor in step.Slot)
                {
                    channel++;
                    var detail = new CellDetail();
                    detail.Channel = channel;
                    detail.Valtage = slor.OcvVal;
                    detail.Ir = slor.AcrVal;

                    details.Add(detail);
                }
                oCVTrayResult.OcvData = details;

                var result1 = await CallOCVResult(oCVTrayResult, str1);
                if (!result1)
                {
                    Log($"{Group.ToString()} OCV 发送组盘结果失败,{oCVTrayResult.TrayNo}", LogEnum.Error);

                }
                else
                {
                    Log($"{Group.ToString()} OCV 发送组盘结果成功,{oCVTrayResult.TrayNo}", LogEnum.Info);
                }





                return;

            }
            else
            {
                Log($"{Group.ToString()} OCV 设备上传信息为空", LogEnum.Error, false);
                return;
            }


        }
        catch (Exception ex)
        {
            Log(ex.Message, LogEnum.Error);
        }

    }

    /// <summary>
    /// 提交OCV结果
    /// </summary>
    /// <param name="data"></param>
    /// <param name="msg"></param>
    /// <returns></returns>
    private async Task<bool> CallOCVResult(OCVTrayResult data, string msg)
    {

        var result = await _connectDataService.CommitOcvResult(data);

        if (result.IsSuccess)
        {
            if (result.Data == null || result.Data.Cells == null || result.Data.Cells.Count == 0)
            {
                Log($" OCV {data.TrayNo} 提交组盘结果失败,FMS电芯结果数据为空,错误Code {result.Code}", LogEnum.Info, false);

                Group.Value = $"OCV {data.TrayNo} OCV 提交组盘结果失败,FMS电芯结果数据为空,错误Code {result.Code}";

                var error = HbcExtension.GenerateHeaderMessage(Group, "", "0204", result.Code.ToString());

                await SendDataToHk(error);
                return false;
            }



            if (result.Data.Rework)
            {

                Group.Value = $"OCV {data.TrayNo} OCV 提交组盘结果成功,进行复测";
                msg = string.Concat(msg, data.TrayNo.PadRight(7, ' '));
                // 发送接收确认
                foreach (var cell in result.Data.Cells)
                {
                    msg += cell.Results;
                }
                msg = HbcExtension.GenerateHeaderMessage(Group, msg, "0205", "0");
            }
            else
            {
                Group.Value = $"OCV {data.TrayNo}OCV 提交组盘结果成功";
                // 0:OK , 1:NG, 4: 在测量超过排放限额
                msg = string.Concat(msg, "0");
                msg = string.Concat(msg, data.TrayNo.PadRight(7, ' '));
                // 发送接收确认
                foreach (var cell in result.Data.Cells)
                {
                    msg += cell.Results;
                }
                msg = HbcExtension.GenerateHeaderMessage(Group, msg, "0204", "0");
                // 提交结果后清空托盘
                Group.TrayNo = String.Empty;
            }

            bool sendResult = await SendDataToHk(msg);

            if (!sendResult)
            {
                sendResult = await SendDataToHk(msg);
            }


            Log($" OCV {data.TrayNo} 提交组盘结果后向设备回复，是否复测 {result.Data.Rework}, 发送是否成功 {sendResult}", LogEnum.Info);

            return sendResult;
        }
        else
        {
            Log($"OCV {data.TrayNo} 发送组盘结果失败,{result.Msg}", LogEnum.Error, false);
            Group.Value = $"OCV {data.TrayNo} 发送组盘结果失败,{result.Msg}";
            var error = HbcExtension.GenerateHeaderMessage(Group, "", "0204", result.Code.ToString());
            await SendDataToHk(error);
            return false;

        }
    }



    public void OCV_ReceiveMessage1204()
    {
    }

    public void OCV_ReceiveMessage1205()
    {
    }
    /// <summary>
    /// 工程结束通知
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task OCV_ReceiveMessage1206(ParserDefine parser)
    {
        string str2 = "";
        str2 = string.Concat(str2, parser.StageNo.PadLeft(4, ' '));
        str2 = string.Concat(str2, parser.TrayID.PadRight(7, ' '));

        var str3 = HbcExtension.GenerateHeaderMessage(Group, str2, "0206", "0");

        await SendDataToHk(str3);


    }
    /// <summary>
    /// 放行通知
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task OCV_ReceiveMessage1207(ParserDefine parser)
    {
        string str2 = "";
        str2 = string.Concat(str2, parser.StageNo.PadLeft(4, ' '));
        str2 = string.Concat(str2, parser.TrayID.PadRight(7, ' '));
        str2 = string.Concat(str2, parser.Mode.PadRight(1, ' '));
        var str3 = HbcExtension.GenerateHeaderMessage(Group, str2, "0207", "0");

        await SendDataToHk(str3);


    }

    /// <summary>
    /// 设备状态通知
    /// </summary>
    /// <param name="parser"></param>
    /// <returns></returns>
    public async Task OCV_ReceiveMessage1209(ParserDefine parser)
    {
        // 完成
        string str4 = "";
        str4 = parser.StageNo.PadLeft(4, ' ');
        // 模式
        Group.Mode = parser.StageMode;




        // retcode 
        var str5 = HbcExtension.GenerateHeaderMessage(Group, str4, "0209", "0");
        await SendDataToHk(str5);


    }
    /// <summary>
    /// 模式切换
    /// </summary>
    /// <param name="group"></param>
    /// <param name="hkWrite"></param>
    /// <returns></returns>
    public async Task OCV_SendMessage0208(HkOcvFmtEquipDto group, HkWriteInstruct hkWrite)
    {
        string sendMsg = hkWrite.Stage.ToString().PadLeft(4, ' ') + hkWrite.Data.PadLeft(1, ' ');

        var headMsg = HbcExtension.GenerateHeaderMessage(group, sendMsg, "0208", "0");



        await SendDataToHk(headMsg);

    }

    public async Task RNK_ReceiveMessage1601()
    {
        var data = HbcExtension.GenerateHeaderMessage(Group, "Cell", "0601", "1");
        await SendDataToHk(data);


    }

    public async Task RNK_ReceiveMessage1602(ParserDefine parser)
    {
        var str3 = parser.StageNo.PadLeft(4, ' ');
        str3 = string.Concat(str3, parser.TrayID.PadLeft(7, ' '));
        string str4 = "";
        str4 = HbcExtension.GenerateHeaderMessage(Group, str3, "0602", "3");
        await SendDataToHk(str4);


    }

    public async Task RNK_ReceiveMessage1603(ParserDefine parser)
    {

        string str7 = "";
        str7 = string.Concat(str7, parser.StageNo.PadLeft(4, ' '));
        str7 = string.Concat(str7, parser.CellId.PadRight(13, ' '));
        string str8 = "";
        str8 = HbcExtension.GenerateHeaderMessage(Group, str7, "0603", "1");
        await SendDataToHk(str8);




    }

    public async Task RNK_ReceiveMessage1604()
    {
        var data = HbcExtension.GenerateHeaderMessage(Group, "Cell", "0604", "1");
        await SendDataToHk(data);


    }

    public void RNK_ReceiveMessage1608()
    {


    }

    public async Task RNK_ReceiveMessage1609(ParserDefine parser)
    {
        string str4 = parser.StageNo.PadLeft(4, ' ');

        var data = HbcExtension.GenerateHeaderMessage(Group, str4, "0609", "1");

        await SendDataToHk(data);


    }
    /// <summary>
    /// rnk模式切换
    /// </summary>
    /// <param name="group"></param>
    /// <param name="hkWrite"></param>
    /// <returns></returns>
    public async Task RNK_SendMessage0608(HkOcvFmtEquipDto group, HkWriteInstruct hkWrite)
    {
        string sendMsg = hkWrite.Stage.ToString().PadLeft(4, ' ') + hkWrite.Data.PadLeft(1, ' ');
        var headMsg = HbcExtension.GenerateHeaderMessage(group, sendMsg, "0608", "0");
        //  var datas= await DataManager.RNK_SendMessage0608(group);

        await SendDataToHk(headMsg);

    }



    public async Task CPK_ReceiveMessage1701(ParserDefine parser)
    {
        string str3 = "";
        str3 = parser.StageNo.PadLeft(4, ' ');
        str3 = parser.TrayID.PadLeft(7, ' ');

        var data = HbcExtension.GenerateHeaderMessage(Group, str3, "0701", "1");
        await SendDataToHk(data);



    }

    public async Task CPK_ReceiveMessage1702(ParserDefine parser)
    {
        var str2 = parser.StageNo.PadLeft(4, ' ');
        str2 = String.Concat(str2, parser.TrayID.PadRight(7, ' '));

        var data = HbcExtension.GenerateHeaderMessage(Group, str2, "0702", "1");
        await SendDataToHk(data);


    }

    public async Task CPK_ReceiveMessage1703(ParserDefine parser)
    {

        var str = parser.StageNo.PadLeft(4, ' ');
        str = string.Concat(str, parser.TrayID.PadRight(7, ' '));

        var data = HbcExtension.GenerateHeaderMessage(Group, str, "0703", "1");

        await SendDataToHk(data);



    }

    public async Task CPK_ReceiveMessage1704(ParserDefine parser)
    {

        var str3 = parser.StageNo.PadLeft(4, ' ');
        str3 = string.Concat(str3, parser.TrayID.PadRight(28, ' '));

        var data = HbcExtension.GenerateHeaderMessage(Group, str3, "0704", "1");
        await SendDataToHk(data);

    }

    public async Task CPK_ReceiveMessage1705(ParserDefine parser)
    {
        var str2 = parser.StageNo.PadLeft(4, ' ');
        str2 = string.Concat(str2, parser.TrayID.PadRight(28, ' '));

        var data = HbcExtension.GenerateHeaderMessage(Group, str2, "0705", "1");
        await SendDataToHk(data);

    }

    public async Task CPK_ReceiveMessage1706(ParserDefine parser)
    {
        var str3 = parser.StageNo.PadLeft(4, ' ');

        var data = HbcExtension.GenerateHeaderMessage(Group, str3, "0706", "1");

        await SendDataToHk(data);


    }

    public async Task CPK_ReceiveMessage1707(ParserDefine parser)
    {
        var str3 = parser.StageNo.PadLeft(4, ' ');
        str3 = string.Concat(str3, parser.TrayID.PadRight(15, ' '));

        var data = HbcExtension.GenerateHeaderMessage(Group, str3, "0707", "1");

        await SendDataToHk(data);


    }

    public async Task CPK_ReceiveMessage1708()
    {


    }

    public async Task CPK_ReceiveMessage1709(ParserDefine parser)
    {


        var str4 = parser.StageNo.PadLeft(4, ' ');

        var data = HbcExtension.GenerateHeaderMessage(Group, str4, "0709", "1");

        await SendDataToHk(data);


    }
    /// <summary>
    /// cpk模式切换
    /// </summary>
    /// <param name="group"></param>
    /// <param name="hkWrite"></param>
    /// <returns></returns>
    public async Task CPK_SendMessage0708(HkOcvFmtEquipDto group, HkWriteInstruct hkWrite)
    {
        // var datas=  await DataManager.CPK_SendMessage0708(group);
        string sendMsg = hkWrite.Stage.ToString().PadLeft(4, ' ') + hkWrite.Data.PadLeft(1, ' ');


        var headMsg = HbcExtension.GenerateHeaderMessage(group, sendMsg, "0708", "0");

        await SendDataToHk(headMsg);

    }


    public async Task ECS_ReceiveMessage1401()
    {

        var data = HbcExtension.GenerateHeaderMessage(Group, "Cell", "0401", "0");

        await SendDataToHk(data);

    }

    public void ECS_ReceiveMessage1402()
    {

    }

    public async Task ECS_ReceiveMessage1403(ParserDefine parser)
    {
        string str3 = "";
        str3 = string.Concat(str3, parser.TransKind.PadLeft(1, ' '));
        str3 = string.Concat(str3, parser.FrPort.PadLeft(3, ' '));
        str3 = string.Concat(str3, parser.ToPort.PadLeft(3, ' '));
        str3 = string.Concat(str3, parser.FrLoc.PadLeft(9, ' '));
        str3 = string.Concat(str3, parser.ToLoc.PadLeft(9, ' '));
        str3 = string.Concat(str3, parser.TrayID.PadRight(7, ' '));
        str3 = string.Concat(str3, parser.TrayID2.PadRight(7, ' '));
        str3 = string.Concat(str3, parser.TrayID3.PadRight(7, ' '));
        str3 = string.Concat(str3, parser.TrayID4.PadRight(7, ' '));
        str3 = string.Concat(str3, parser.TrayID5.PadRight(7, ' '));
        str3 = string.Concat(str3, parser.TrayID6.PadRight(7, ' '));
        str3 = string.Concat(str3, "".PadLeft(20, ' '));

        var data = HbcExtension.GenerateHeaderMessage(Group, str3, "0403", "0");
        await SendDataToHk(data);



    }

    public void ECS_ReceiveMessage1406()
    {

    }

    public async Task ECS_ReceiveMessage1407(ParserDefine parser)
    {

        var str1 = parser.StageNo.Trim().PadLeft(3, ' ');
        str1 = string.Concat(str1, parser.GroupNum.Trim().PadLeft(4, ' '));
        str1 = string.Concat(str1, parser.ErrCode.Trim().PadLeft(1, ' '));

        var data = HbcExtension.GenerateHeaderMessage(Group, str1, "0407", "0");

        await SendDataToHk(data);

    }

    public void ECS_ReceiveMessage1408()
    {

    }

    public void ECS_ReceiveMessage1411()
    {

    }

    public void ECS_ReceiveMessage1412()
    {

    }

    public void ECS_ReceiveMessage1413()
    {

    }

    public void ECS_SendMessage0402()
    {

    }

    #endregion

    public void AppendMsgQ(string msg)
    {
        int num = 0;
        while (num < 101)
        {
            if (TxCnt[num] <= 0)
            {
                TxCnt[num] = msg.Length;
                TxMsg[num] = msg;
                break;
            }
            else
            {
                num++;
            }
        }
    }
    /// <summary>
    /// 记录日志
    /// </summary>
    /// <param name="log"></param>
    /// <param name="logType"></param>
    private void Log(string log, LogEnum logType, bool isSuccess = true)
    {
        OnConnectLogChanged?.Invoke(this, new ConnectStatusEventArgs
        {
            Connect = _tcpClient.Connected,
          
            Message = log,
            IsSuccess = true
        });
    }
    public async Task<bool> SendMessage()
    {
        if (_curConnection)
        {
            int num = 0;
            while (num < 101)
            {
                if (TxCnt[num] != 0)
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(TxMsg[num]);
                    try
                    {
                        await _stream.WriteAsync(bytes, 0, (int)bytes.Length);
                        Group.ReadTime = DateTime.Now;

                    }
                    catch (Exception ex)
                    {
                        var error = $"{Group.Name} PC IMS SendData Error,{ex.Message}";
                        Log(error, LogEnum.Error);
                        return false;
                    }
                    num++;
                }
                else
                {
                    break;
                }
            }
            CompressMsgQ();
            return true; ;
        }
        else
        {
            return false;
        }
    }


    public void CompressMsgQ()
    {
        int num = 0;
        while (num < 101)
        {
            if (TxCnt[num] != 0)
            {
                TxCnt[num] = 0;
                TxMsg[num] = "";
                num++;
            }
            else
            {
                break;
            }
        }
    }

    //public void ServerConnectedCheck(string hostIP, int hostPort)
    //{

    //    TcpConnectionInformation[] activeTcpConnections = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections();
    //    int num = 0;
    //    while (num < (int)activeTcpConnections.Length)
    //    {
    //        TcpConnectionInformation tcpConnectionInformation = activeTcpConnections[num];
    //        if ((tcpConnectionInformation.RemoteEndPoint.Address.ToString() != hostIP ? true : tcpConnectionInformation.RemoteEndPoint.Port != hostPort))
    //        {
    //            num++;
    //        }
    //        else
    //        {
    //            if (tcpConnectionInformation.State == TcpState.Established)
    //            {


    //            }
    //            break;
    //        }
    //    }

    //}
    /// <summary>
    /// 发送心跳
    /// </summary>
    /// <returns></returns>
    public async Task COM_SendMessage0001()
    {
        string retcode = "0";
        string sdata = "";
        string bdata = "";
        sdata = HbcExtension.GenerateHeaderMessage(Group, bdata, "0001", "0");
        AppendMsgQ(sdata);
        await SendMessage();
    }
    /// <summary>
    /// 发送数据给hk
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    private async Task<bool> SendDataToHk(string msg)
    {
        if (!string.IsNullOrEmpty(msg))
        {
            AppendMsgQ(msg);
            return await SendMessage();
        }
        return false;
    }
    /// <summary>
    /// 0103 入库完成通知
    /// </summary>
    /// <exception cref="NotImplementedException"></exception>
    internal async Task FMT_SendMessage0103(HkOcvFmtEquipDto group, HkWriteInstruct hkWrite)
    {






        ParserDefine parser = new ParserDefine();

        parser.StageNo = hkWrite.Stage.ToString();
        parser.TrayID = hkWrite.TrayID;

        string sendMsg = parser.StageNo.PadLeft(4, ' ') + parser.TrayID.PadLeft(7, ' ');

        var headMsg = HbcExtension.GenerateHeaderMessage(group, sendMsg, "0103", "0");


        await SendDataToHk(headMsg);


    }

    /// <summary>
    ///  0102 入库预约通知
    /// </summary>
    /// <param name="group"></param>
    /// <param name="data"></param>
    /// <param name="type">1复测 2重新作业</param>
    /// <returns></returns>
    internal async Task<bool> FMT_SendMessage0102(HkOcvFmtEquipDto group, HkWriteInstruct data, int type = 0)
    {



        // 获取配方
        bool isRetest = false;
        if (type == 1)
        {
            isRetest = true;
        }
        bool chargeResult = false;
        if (Group.Num == data.Num)
        {
            var stage = Group.Stages.FirstOrDefault(x => x.StageNo == data.Stage.ToString());


            if (stage != null && stage.StageStatus == "6")
            {
                stage.Status = 1;
            }


            stage.Status = 1;



            // 向设备发送数据
            chargeResult = await SendChargeStartData(stage.StageNo, data.TrayID, isRetest);

        }

        // 来自双叉库位信息
        if (Group.Num == data.Num2)
        {
            // 双叉库位
            if (data.Stage2 > 0)
            {
                var stage2 = Group.Stages.FirstOrDefault(x => x.StageNo == data.Stage2.ToString());
                if (stage2 != null)
                {
                    if (stage2.StageStatus == "6")
                    {
                        stage2.Status = 1;
                    }

                    stage2.Status = 1;

                    // 向设备发送数据
                    chargeResult = await SendChargeStartData(stage2.StageNo, data.TrayID2);





                }

            }
        }


        return chargeResult;














    }
    /// <summary>
    ///  获取配方数据后进行发送
    /// </summary>
    /// <param name="stage"></param>
    /// <param name="trayID"></param>
    /// <param name="isRetest">是否复测</param>
    /// <returns></returns>
    private async Task<bool> SendChargeStartData(string stage, string trayID, bool isRetest = false)
    {
        GrpcReturn<string> result = new GrpcReturn<string>();

        if (isRetest)
        {
            result = await _connectDataService.GetReTestChargeFMT(new HkWriteInstruct
            {
                TrayID = trayID,
                Stage = int.Parse(stage),
                Num = Group.Num

            });
        }
        else
        {
            result = await _connectDataService.GetChargeFMTData(new HkWriteInstruct
            {
                TrayID = trayID,
                Stage = int.Parse(stage),
                Num = Group.Num

            });
        }


        if (result.IsSuccess && result.Data.IsNotNullOrEmpty())
        {
            Group.Value = $"Num {Group.Num} stage {stage} trayID {trayID} 获取 {(isRetest == true ? "复测" : "")} 配方数据成功";
            var sendCode = result.Data;






            var msg = HbcExtension.GenerateHeaderMessage(Group, sendCode, "0102", "0");

            await SendDataToHk(msg);

            return true;
        }
        else
        {
            var msg = $"Num {Group.Num} stage {stage} trayID {trayID} 获取 {(isRetest == true ? "复测" : "")} 配方数据失败 {result.Msg}";
            Group.Value = msg;
            Log($"Num {Group.Num} stage {stage} trayID {trayID} 获取 {(isRetest == true ? "复测" : "")} 配方数据失败 {result.Msg}", LogEnum.Error, false);
            return false;
        }
    }

    private async Task<string> SendComplexData(string stageNo)
    {

        string text10 = "";
        //text10 += "StageNo".PadLeft(4, ' ');
        text10 += stageNo.PadLeft(4, ' ');
        //text10 += "TypeNo".PadLeft(4, ' ');
        text10 += "P103".PadLeft(4, ' ');
        //text10 += "ProcNo".PadLeft(2, ' ');
        text10 += "02".PadLeft(2, ' ');
        //text10 += "Lot".PadLeft(10, ' ');
        text10 += "ELKV22X".PadLeft(10, ' ');
        //text10 += "TrayID".PadRight(7, ' ');

        text10 += "A000001".PadRight(7, ' ');

        // FMT(Charge Discharge), PRE(Pre Charge), DCR
        text10 += "PRE".PadLeft(3, ' ');


        text10 += "3".ToString().Trim().PadLeft(2, ' ');

        #region Step Setting
        List<string> stepSetting = new List<string>();
        string step1 = string.Empty;
        step1 += "1".PadLeft(2, ' ');
        // 2 REST  3 CC  2 REST
        step1 += "2".PadLeft(1, ' ');
        // 恒压
        step1 += "0".PadLeft(7, ' ');
        // 恒电流
        step1 += "0".PadLeft(7, ' ');
        // 时间
        step1 += "1".PadLeft(7, ' ');
        // 终止电压
        step1 += "0".PadLeft(7, ' ');
        // 终止电流
        step1 += "0".PadLeft(7, ' ');
        // 终止容量
        step1 += "0".PadLeft(7, ' ');

        // 限制检验时间
        step1 += "0".PadLeft(5, ' ');

        stepSetting.Add(step1);

        string step2 = string.Empty;

        step2 += "2".PadLeft(2, ' ');
        // 2 REST  3 CC  2 REST
        step2 += "3".PadLeft(1, ' ');
        // 恒压
        step2 += "3600".PadLeft(7, ' ');
        // 恒电流
        step2 += "340".PadLeft(7, ' ');
        // 时间
        step2 += "1".PadLeft(7, ' ');
        // 终止电压
        step2 += "4250".PadLeft(7, ' ');
        // 终止电流
        step2 += "0".PadLeft(7, ' ');
        // 终止容量
        step2 += "0".PadLeft(7, ' ');
        // 限制检验时间
        step2 += "0".PadLeft(5, ' ');

        stepSetting.Add(step2);

        //string step3 = string.Empty;
        //step3 += "3".PadLeft(2, ' ');
        //// 2 REST  3 CC  2 REST
        //step3 += "2".PadLeft(1, ' ');
        //// 恒压
        //step3 += "0".PadLeft(7, ' ');
        //// 恒电流
        //step3 += "0".PadLeft(7, ' ');
        //// 时间
        //step3 += "3".PadLeft(7, ' ');
        //// 终止电压
        //step3 += "0".PadLeft(7, ' ');
        //// 终止电流
        //step3 += "0".PadLeft(7, ' ');
        //// 终止容量
        //step3 += "0".PadLeft(7, ' ');
        //// 限制检验时间
        //step3 += "0".PadLeft(5, ' ');

        //stepSetting.Add(step3);

        foreach (var setting in stepSetting)
        {
            text10 += setting;
        }

        #endregion

        #region Protect Setting
        // 充电上限电压
        text10 += "4250".PadLeft(4, ' ');
        // 充电上限容量
        text10 += "3800".PadLeft(4, ' ');
        // 充电电流下限
        text10 += "50".PadLeft(4, ' ');
        // 充电下降电压检查时间 sec
        text10 += "0".PadLeft(5, ' ');
        // 充电下限电压检查 mA
        text10 += "0".PadLeft(4, ' ');
        // T1时刻检查时间 
        text10 += "0".PadLeft(5, ' ');
        // T1时刻电压上限
        text10 += "0".PadLeft(4, ' ');
        // T1时刻电压下限
        text10 += "0".PadLeft(4, ' ');
        // T2时刻检查时间
        text10 += "0".PadLeft(5, ' ');
        // T2时刻电压上限
        text10 += "0".PadLeft(4, ' ');
        // T2时刻电压下限
        text10 += "0".PadLeft(4, ' ');
        // T3小时
        text10 += "0".PadLeft(5, ' ');
        // T4小时
        text10 += "0".PadLeft(5, ' ');
        // T5时刻检查时间
        text10 += "0".PadLeft(5, ' ');
        // T5时刻电流上限
        text10 += "0".PadLeft(4, ' ');

        // T5时刻电流下限
        text10 += "0".PadLeft(4, ' ');

        // 恒定充电电压偏差
        text10 += "0".PadLeft(4, ' ');

        // 充电电流上升累计次数
        text10 += "10".PadLeft(3, ' ');

        // 充电电流上升连续次数
        text10 += "5".PadLeft(3, ' ');

        // 充电电压下降累计次数
        text10 += "10".PadLeft(3, ' ');

        // 充电电压下降连续次数
        text10 += "5".PadLeft(3, ' ');

        // 充电时间超时 sec
        text10 += "10800".PadLeft(5, ' ');

        // 充电电压下限 mv
        text10 += "2000".PadLeft(4, ' ');

        // 放电时间超时
        text10 += "7200".PadLeft(5, ' ');

        // 放电容量设定信息保护值 mv
        text10 += "0".PadLeft(4, ' ');

        // 放电电压上升累计回收
        text10 += "10".PadLeft(3, ' ');

        // 放电电压上升连续次数
        text10 += "5".PadLeft(3, ' ');

        // 恒定电流波动
        text10 += "50".PadLeft(4, ' ');

        // 电流过大 mA
        text10 += "4000".PadLeft(4, ' ');

        // 休眠时电路电流 mA
        text10 += "500".PadLeft(4, ' ');

        // 电压过大 mA
        text10 += "4250".PadLeft(4, ' ');

        // 电流线电压过大 mA
        text10 += "4800".PadLeft(4, ' ');

        // 放电时间电压差 mA
        text10 += "0".PadLeft(4, ' ');

        // 休眠时间电压差 mA
        text10 += "0".PadLeft(4, ' ');

        // 接触电阻 mQ
        text10 += "10".PadLeft(4, ' ');

        // 电压突变
        text10 += "50".PadLeft(2, ' ');

        // 注意温度 
        text10 += "45".PadLeft(2, ' ');

        // 电芯温度警报
        text10 += "60".PadLeft(2, ' ');

        // 电流百分比
        text10 += "10".PadLeft(3, ' ');

        // 初始电压上限 mA
        text10 += "430".PadLeft(4, ' ');

        // 初始电压下限 mA
        text10 += "50".PadLeft(4, ' ');

        // 完成电压上限 mA
        text10 += "3490".PadLeft(4, ' ');

        // 完成电压下限 mA
        text10 += "3390".PadLeft(4, ' ');

        // 一次放电容量上限 mA
        text10 += "3500".PadLeft(4, ' ');
        // 一次放电容量下限 mA
        text10 += "100".PadLeft(4, ' ');
        // 二次放电容量上限 mA
        text10 += "3800".PadLeft(4, ' ');
        // 二次放电容量下限 mA
        text10 += "100".PadLeft(4, ' ');

        #endregion

        #region Contack Setting
        // 充电电压 mV
        text10 += "4200".PadLeft(5, ' ');
        // 充电电流 mA
        text10 += "50".PadLeft(4, ' ');
        // 起始时间检测 sec
        text10 += "2".PadLeft(2, ' ');
        // 充电截止时间
        text10 += "15".PadLeft(2, ' ');
        // 电压检查 mV
        text10 += "4200".PadLeft(5, ' ');
        // 反向电压 mV
        text10 += "-4200".PadLeft(5, ' ');
        // 电压上限值 mV
        text10 += "4200".PadLeft(5, ' ');
        // 电压下限 mV
        text10 += "100".PadLeft(5, ' ');
        // 电压最大变化 mV
        text10 += "1500".PadLeft(5, ' ');
        // 电压最小变化 mV
        text10 += "4200".PadLeft(5, ' ');

        // 电流偏差 %
        text10 += "90".PadLeft(3, ' ');

        #endregion
        // 报警发生个数
        text10 += "3".PadLeft(3, ' ');



        // 0 : OK, 1 : 之前工程不良, 2 : No Cell
        for (int num5 = 0; num5 < 400; num5++)
        {
            if (num5 == 0)
            {
                text10 += "0";
            }
            else
            {
                text10 += "2".PadLeft(1, ' ');
            }

        }


        var msg = HbcExtension.GenerateHeaderMessage(Group, text10, "0102", "0");

        return msg;

    }


    /// <summary>
    /// 0107 出库完成通知
    /// </summary>
    /// <exception cref="NotImplementedException"></exception>
    internal async Task FMT_SendMessage0107(HkOcvFmtEquipDto group, HkWriteInstruct write)
    {

        string sendMsg = write.Stage.ToString().PadLeft(4, ' ');

        var headMsg = HbcExtension.GenerateHeaderMessage(group, sendMsg, "0107", "0");

        await SendDataToHk(headMsg);
    }


    /// <summary>
    /// 0105 结果File要求
    /// </summary>
    /// <param name="group"></param>
    /// <returns></returns>
    internal async Task FMT_SendMessage0105(HkOcvFmtEquipDto group, HkWriteInstruct write)
    {
        string sendMsg = write.Stage.ToString().PadLeft(4, ' ') + write.TrayID.PadLeft(7, ' ');

        var headMsg = HbcExtension.GenerateHeaderMessage(group, sendMsg, "0105", "0");

        await SendDataToHk(headMsg);

    }
    /// <summary>
    /// 0108 Mode变更要求 调度远程修改库位模式
    /// </summary>
    /// <param name="group"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    internal async Task FMT_SendMessage0108(HkOcvFmtEquipDto group, HkWriteInstruct hkWrite)
    {

        string sendMsg = hkWrite.Stage.ToString().PadLeft(4, ' ') + hkWrite.Data.PadLeft(1, ' ');


        var headMsg = HbcExtension.GenerateHeaderMessage(group, sendMsg, "0108", "0");


        await SendDataToHk(headMsg);


    }
}
